package com.dash.dashupload;

import com.dash.pojo.Video;

import android.os.AsyncTask;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DashServer {

	private volatile static DashServer instance = null;
	private ServerCommunicateUtil serverCommunicateUtil;

	private DashServer() {
		this.serverCommunicateUtil = new ServerCommunicateUtil();
	}

	public static DashServer getInstance() {
		// 先检查实例是否存在，如果不存在才进入下面的同步块
		if (instance == null) {
			// 同步块，线程安全的创建实例
			synchronized (DashServer.class) {
				// 再次检查实例是否存在，如果不存在才真正的创建实例
				if (instance == null) {
					instance = new DashServer();
				}
			}
		}
		return instance;
	}

	public int uploadFile(Video[] video,
			TextView textView, ProgressBar progressBar) {
		// first query server whether the video status to found it is a new
		// upload
		// or it is a resume upload or it is already uploaded
		int status = serverCommunicateUtil.getVideostatus(video[0].getTitle(), video[0].getSegmentTotal());
		switch (status) {
		case DashMessage.UPLOAD_NOTFOUND:
			// upload new file
			new UploadTask(textView, progressBar).execute(video);
			break;
		case DashMessage.UPLOAD_FINISHED:
			// already exist do nothing
			break;
		default:
			// resume upload file status is how many segements server received
			// construct String array that the first one is how many uploaded
			/*String[] newSrcPath = new String[srcPaths.length + 1];
			newSrcPath[0] = status + "";*/
			for(int i=0;i<status;i++){
				video[i].setUpload(true);
			}
			// AsyncTask.THREAD_POOL_EXECUTOR,
			// new ResumeUploadTask(textView, progressBar).execute(newSrcPath);
			new ResumeUploadTask(textView, progressBar).executeOnExecutor(
					AsyncTask.THREAD_POOL_EXECUTOR, video);
			break;
		}
		return status;
	}
}
